//
//  SpecialDetailViewController.m
//  Trip
//
//  Created by mingyang on 15-7-14.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "SpecialDetailViewController.h"
#import "ArticleSections.h"
#import "Database.h"
#import <ShareSDK/ShareSDK.h>
@interface SpecialDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, retain) NSMutableArray *article;
@property (nonatomic, retain) NSArray *cacheArr;
@property (nonatomic, retain) UIButton *shareBtn;
@property (nonatomic, retain) UIButton *collectBtn;
@end

@implementation SpecialDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    [view release];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Navbar_mask"] forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"BackBorderBarButton"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
    
    //定义菊花控件
    self.activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:self.activityIndicator];
    self.activityIndicator.color = [UIColor grayColor];
    self.activityIndicator.center = self.view.center;
    [self.activityIndicator release];
    [self.activityIndicator startAnimating];
    
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *shareBtn = [UIImage imageNamed:@"ShareBorderBarButton"];
    shareBtn = [shareBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.shareBtn setImage:shareBtn forState:UIControlStateNormal];
    self.collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *collectBtn = [UIImage imageNamed:@"FavoriteBorderBarButton"];
    collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
    self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 80, 5, 30, 30);
    self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 46, 3, 32, 32);
    [self.shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.collectBtn addTarget:self action:@selector(collect) forControlEvents:UIControlEventTouchUpInside];
    self.collectBtn.hidden = NO;
    self.shareBtn.hidden = NO;
    self.collectBtn.enabled = NO;
    self.shareBtn.enabled = NO;
    [self judgeCollectState];
    [self.navigationController.navigationBar addSubview:self.shareBtn];
    [self.navigationController.navigationBar addSubview:self.collectBtn];
    //[self activityIndicator];
    [self getData];
    
}
- (void)share
{
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    id<ISSContent> publishContent = [ShareSDK content:@"分享内容:"
                                       defaultContent:@"测试一下"
                                                image:nil
                                                title:@"ShareSDK"
                                                  url:@"http://www.mob.com"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}

- (void)collect
{
    NSArray *array = [Database selectData];
    int i = 0;
    specialDetail *specialDetail = self.cacheArr.lastObject;
    for (DbModel *model in array) {
        if (model.titleId == self.number) {
            i = 1;
            break;
        }
    }
    if (i == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您已经收藏过此篇专题!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        alert.tag = 1;
        [alert show];
    } else {
        DbModel *model = [DbModel getDbModel];
        model.title = specialDetail.name;
        model.titleId = self.number;
        model.choose = 1;
        model.imageURL = specialDetail.image_url;
        [Database insertValue:model];
        UIImage *collectBtn = [UIImage imageNamed:@"FavoritedBorderBarButton"];
        collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        alert.tag = 1;
        [alert show];
    }
}
- (void)judgeCollectState
{
    NSArray *array = [Database selectData];
    int i = 0;
    for (DbModel *model in array) {
        if (model.titleId == self.number) {
            i = 1;
            break;
        }
    }
    if (i == 1) {
        UIImage *collectBtn = [UIImage imageNamed:@"FavoritedBorderBarButton"];
        collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
    } else {
        UIImage *collectBtn = [UIImage imageNamed:@"FavoriteBorderBarButton"];
        collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
    }
}
-(void)createSpeDetailTableView
{
    self.speDetailTalbleView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.speDetailTalbleView.dataSource = self;
    self.speDetailTalbleView.delegate = self;
    [self.view addSubview:self.speDetailTalbleView];
    [self createHeaderImg];
    self.speDetailTalbleView.tableHeaderView = self.headerImg;
    [_speDetailTalbleView release];
}

-(void)createHeaderImg
{
    self.headerImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    
    self.back = [[UIImageView alloc]initWithFrame:CGRectMake(0, 70, self.headerImg.frame.size.width, 120)];
    self.back.image = [UIImage imageNamed:@"back"];
    [self.headerImg addSubview:self.back];
    
    self.headerName = [[UILabel alloc]initWithFrame:CGRectMake(0, 70, self.headerImg.frame.size.width, 40)];
    self.headerName.textColor = [UIColor whiteColor];
    [self.headerName setFont:[UIFont fontWithName:@"Helvetica-Bold" size:25]];
    self.headerName.textAlignment = NSTextAlignmentCenter;
    self.headerName.backgroundColor = [UIColor clearColor];
    
    self.headerTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 120, self.headerImg.frame.size.width, 30)];
    self.headerTitle.textColor = [UIColor whiteColor];
    [self.headerTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
    self.headerTitle.textAlignment = NSTextAlignmentCenter;
    self.headerTitle.backgroundColor = [UIColor clearColor];
    [self.headerImg addSubview:self.headerTitle];
    [self.headerImg addSubview:self.headerName];

    [_headerImg release];
    [_headerName release];
    [_headerTitle release];
    [_back release];
    
    
}
-(void)getData
{
    NSString *str = [NSString stringWithFormat:@"http://chanyouji.com/api/articles/%ld.json?page=1", (long)self.number];
    [AFNetworkHandler GetWithAFNByURL:str completion:^(id result) {
        NSDictionary *tempDic = result;
        NSMutableArray *temp = [NSMutableArray array];
        [temp addObject:tempDic];
        self.article = [NSMutableArray array];
        NSMutableArray *arr = [NSMutableArray array];
        arr = [specialDetail arrayWithModelByArray:temp];
        self.arr = [NSMutableArray array];
        for (specialDetail *s in arr) {
            [self.arr addObject:s];
        }
        self.cacheArr = [NSArray array];
        self.cacheArr = self.arr;
        [self createSpeDetailTableView];
        
        [self.headerImg setImageWithURL:[NSURL URLWithString:[[self.arr lastObject] image_url]] placeholderImage:[UIImage imageNamed:@"place_holder.jpg"]];
        self.headerName.text = [[self.arr lastObject] name];
        self.headerTitle.text = [[self.arr lastObject] title];
        self.hiddenImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, -(200 - 64), self.view.bounds.size.width, 200)];
        [self.hiddenImg setImageWithURL:[NSURL URLWithString:[[self.arr lastObject] image_url]] placeholderImage:[UIImage imageNamed:@"place_holder.jpg"]];
        [self.view addSubview:self.hiddenImg];
        self.hiddenImg.hidden = YES;

        for (specialDetail *s in self.arr) {
            NSArray *array = [NSArray array];
            array = s.article_sections;
            for (NSDictionary *dic in array) {
                ArticleSections *a = [[ArticleSections alloc] initWithDic:dic];
                [self.article addObject:a];
            }
        }
        [self.activityIndicator stopAnimating];
        self.collectBtn.enabled = YES;
        self.shareBtn.enabled = YES;
    }];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SpecialDetailTableViewCell *cell = [[UITableView alloc]dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        cell = [[[SpecialDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"]autorelease];
    }
    cell.a = self.article[indexPath.row];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.article.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat h1 = [SpecialDetailTableViewCell heightWithText:[self.article[indexPath.row] specialDescription]];
    CGFloat h2 = [SpecialDetailTableViewCell getImageViewHeight:[[self.article[indexPath.row] image_width] floatValue] andHeight:[[self.article[indexPath.row] image_height] floatValue]];
    //CGFloat h3 = [SpecialDetailTableViewCell heightWithText:[self.article[indexPath.row]title]];
    if (NO == [[self.article[indexPath.row] specialDescription] isEqual:[NSNull null]] && [[self.article[indexPath.row] image_url] isEqualToString:@""] == YES) {
        return h1 + 10;
    } else if (YES == [[self.article[indexPath.row] specialDescription] isEqual:[NSNull null]] && [[self.article[indexPath.row] image_url] isEqualToString:@""] == NO){
        return h2;
    } else if (NO == [[self.article[indexPath.row] specialDescription] isEqual:[NSNull null]] && [[self.article[indexPath.row] image_url] isEqualToString:@""] == NO){
        return h1 + h2 + 15;
    } else {
        return 0;
    }
}

-(void)back:(UIButton *)btn
{
    self.collectBtn.hidden = YES;
    self.shareBtn.hidden = YES;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.speDetailTalbleView.contentOffset.y >= (200 - 64)) {
        self.hiddenImg.hidden = NO;
        self.speDetailTalbleView.tableHeaderView = nil;
        self.speDetailTalbleView.frame = CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height);
    }else if (self.speDetailTalbleView.contentOffset.y < (200 - 64)){
        self.hiddenImg.hidden = YES;
        self.speDetailTalbleView.tableHeaderView = self.headerImg;
        self.speDetailTalbleView.frame = self.view.frame;
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
